const util = require('../../../utils/util.js');
const barTitleText = ['投保信息','投保人信息','投保方案'];
const app = getApp();
const extraList = ['投保','不投保'];
Page({
  data: {
    insuranceinfo:{
      quotationCarId:'',
      carId:'',
      carPhoto: '../../../images/addcar.png',
      licencePlate:'车牌号',
      carTypeName:'车辆类型',
      carBelongName:'车辆所属',
      insureArea:'',
      ifTransferAfterFirstInsure:1,
      applicantName:'',
      applicantPhoneNumber:'',
      applicantIdentityCard:'',
      insuranceFirstBeneficiary:'',
      applicantIdentityCardFront:'../../../images/id.jpg',
      applicantIdentityCardReverse:'../../../images/id1.jpg'
    },
    insuranceKindList:[],
    images: [],
    /*地址 */
    region: ["广东省", "中山市"],
    customItem: '全部',
    /*单选 */
    items: [
      { value: 1, text:'中国人寿'},
      { value: 2, text:'中国人保'},
      { value: 3, text: '阳光保险' },
      { value: 4, text: '华泰保险' },
      { value: 5, text: '太平洋保险' }
    ],

    activeDot: 0,
    activeDotList: util.createDotList(3, 0),
  },
  radioChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    this.data.insuranceinfo.ifTransferAfterFirstInsure = e.detail.value;
  },
  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    const targetArea = e.detail.value;
    this.setData({
      region: targetArea,
      ['insuranceinfo.insureArea']: targetArea.join(' ')
    })
  },

  onLoad: function (e) {
    if (e.insuranceQuotationId){
      this.data.insuranceQuotationId = e.insuranceQuotationId;
      this.getInsuranceInfo();
    }
  },

  onShow:function(){
    if(this.data.activeDot === 0){
      if(app.globalData.carInfo){
        const carInfo = app.globalData.carInfo;
        this.setData({
          ['insuranceinfo.carId']:carInfo.carId,
          ['insuranceinfo.carPhoto']: carInfo.carPhoto,
          ['insuranceinfo.licencePlate']: carInfo.licencePlate,
          ['insuranceinfo.carTypeName']: carInfo.carType,
          ['insuranceinfo.carBelongName']:  carInfo.carBelong || '个人',

        },res => {
          app.globalData.carInfo = null;
        })
      }
    }
  },


  onGetCarInfo:function(){
    wx.navigateTo({
      url: '../../vehicleBound/index/index?type=select',
    });
  },

  onInput:function(e){
    const name = e.currentTarget.dataset.name,
          value = e.detail.value;
    this.data.insuranceinfo[name] = value;
  },

  onChooseUpload(e) {
    const name = e.currentTarget.dataset.name;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      success: res => {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        this.uploadImage(tempFilePaths[0],name)
          .then(res => {
            this.setData({
              [`insuranceinfo.${name}`]: JSON.parse(res.data).data.imgPath
            });
          });
      }
    })
  },

  uploadImage: function (file,name) {
    return new Promise((resolve,reject) => {
      wx.showLoading({
        title: '正在上传',
      });
      wx.uploadFile({
        url: 'https://www.shencheyi.com/api/v1/Files/Img',
        filePath: file,
        name: name,
        success: res => {
          wx.hideLoading();
          wx.showToast({
            title: '上传成功',
          });
          resolve(res);
        },

      })
    });
    
  },

  onPickerChange: function (e) {
    const value = parseInt(e.detail.value),
          index = e.currentTarget.dataset.index,
          insuranceKindList = this.data.insuranceKindList;
    this.setData({[`insuranceKindList[${index}].schemeText`]: insuranceKindList[index].insuranceKindNameList[value]});
  },

  onCheckboxChange:function(e){
    const index = e.currentTarget.dataset.index,
          value = e.detail.value;
    console.log(e);
    value.forEach(item => {
      this.data.insuranceKindList[item].ifSDEW = 1;
    });    
  },
  onChooseScheme:function(e){
    const index = e.currentTarget.dataset.index,
          itemList = this.data.insuranceKindList[index].insuranceKindDetailList.map(item => {
            return item.name;
          });
    wx.showActionSheet({
      itemList: itemList,
      success:res => {
        this.setData({ [`insuranceKindList[${index}].schemeText`]: itemList[res.tapIndex]});
      }
    })
  },
  //还未检查参数合法
  submitForm: function() {
    //第一步提交
    (() => {
      // return new Promise((res,rej) => {res()});
      const insuranceInfo = this.data.insuranceinfo;
      if (this.data.activeDot === 0) {
        let postInfo = {
          userId: app.globalData.userId,
          CarId: insuranceInfo.carId || insuranceInfo.quotationCarId,
          ifTransferAfterFirstInsure: insuranceInfo.ifTransferAfterFirstInsure,
          insureArea: insuranceInfo.insureArea
        }
        //已创建过
        if (this.data.insuranceQuotationId) {
          postInfo.insuranceQuotationId = this.data.insuranceQuotationId;
          postInfo.quotationCarId = insuranceInfo.quotationCarId || insuranceInfo.carId ;
          return this.insuranceFirst(postInfo);
        } else {
          return this.insuranceCreate(postInfo);
        }
      } else if (this.data.activeDot === 1){
        //第二步
        let postInfo = {
          insuranceQuotationId: this.data.insuranceQuotationId,
          applicantName: insuranceInfo.applicantName,
          applicantIdentityCard: insuranceInfo.applicantIdentityCard,
          applicantPhoneNumber: insuranceInfo.applicantPhoneNumber,
          insuranceFirstBeneficiary: '',
          applicantIdentityCardFront: insuranceInfo.applicantIdentityCardFront,
          applicantIdentityCardReverse: insuranceInfo.applicantIdentityCardReverse
        };
        if (postInfo.applicantIdentityCardFront === "../../../images/id.jpg") {
          postInfo.applicantIdentityCardFront = ''
        }
        if (postInfo.applicantIdentityCardReverse === "../../../images/id1.jpg"){
          postInfo.applicantIdentityCardReverse = ''
        }
        return this.insuranceSecond(postInfo);
      }else{
        //最后一步
        let postInfo = {
          insuranceQuotationId: this.data.insuranceQuotationId,
        };
        postInfo.kindList = this.data.insuranceKindList.map(item => {
          return {
            kind: item.insuranceQuotationDetail.insuranceKind,
            kindDetail: item.schemeText,
            ifSDEW: item.ifSDEW
}
        });
        console.log(postInfo);
        return this.insuranceThirdly(postInfo);

      }
    })()
      .then(res => {
        if(this.data.activeDot === 0){
          console.log(this.data.insuranceQuotationId)
          this.getInsuranceKindList(this.data.insuranceQuotationId);
        }
        if (this.data.activeDot !== 2){
          this.nextStep();
        }else{
          wx.showModal({
            title: '提示',
            content: '保险报价单已提交成功，客服会尽快与您取得联系，商讨业务细节',
            showCancel:false,
            success:() => {
              wx.navigateBack();
            }
          });
        }
      });
  },
  insuranceFirst: function (postInfo){
    return new Promise((resolve, reject) => {
      app.request('/Insurance/InsuranceFirst', 'PUT', postInfo,
        res => {
          resolve(res);
        }, '信息保存失败');
    });
  },
  insuranceSecond: function (postInfo) {
    return new Promise((resolve, reject) => {
      app.request('/Insurance/InsuranceSecond', 'PUT', postInfo,
        res => {
          resolve(res);
        }, '信息保存失败');
    });
  },
  insuranceThirdly: function (postInfo) {
    return new Promise((resolve, reject) => {
      app.request('/Insurance/InsuranceThirdly', 'PUT', postInfo,
        res => {
          resolve(res);
        }, '信息保存失败');
    });
  },
  insuranceCreate: function (postInfo){
    return new Promise((resolve, reject) => {
      app.request('/insurance/Create', 'POST', postInfo,
        res => {
          this.data.insuranceQuotationId = res.insuranceQuotationId;
          resolve(res);
        }, '保险单创建失败');
    });
  },
  //加载保险具体信息
  getInsuranceInfo:function(){
      app.request('/Insurance/Insurance', 'GET', { insuranceQuotationId: this.data.insuranceQuotationId },
        res => {
          console.log('加载保险具体信息', res);
          res.insuranceQuotation.carPhoto = res.SCY_QuotationCarModel.carPhoto;
          res.insuranceQuotation.licencePlate = res.SCY_QuotationCarModel.licencePlate;
          res.insuranceQuotation.carTypeName = res.SCY_QuotationCarModel.carTypeName || '小车';
          res.insuranceQuotation.applicantIdentityCardFront = res.insuranceQuotation.applicantIdentityCardFront || '../../../images/id.jpg';
          res.insuranceQuotation.applicantIdentityCardReverse = res.insuranceQuotation.applicantIdentityCardReverse || '../../../images/id1.jpg';
          this.data.items.forEach(item => {
            if (item.value === res.insuranceQuotation.ifTransferAfterFirstInsure){
              item.checked = true;
            }else{
              item.checked = false;
            }
          });
          this.setData({
            insuranceinfo: res.insuranceQuotation,
            items:this.data.items
          });
        }, '获取失败');
  },

  getInsuranceKindList:function(){
    //加载保险种类
    app.request('/Insurance/InsuranceDedail', 'GET', { insuranceQuotationId: this.data.insuranceQuotationId},
      res => {
        console.log(res);
        res.list.forEach(item => {
          if (item.insuranceKindDetailList.length) {
            item.schemeText = item.insuranceKindDetailList[0].name;
            item.ifSDEW = 0;
            item.insuranceKindNameList = item.insuranceKindDetailList.map(insurance => insurance.name);
          }
        });
        this.setData({
          insuranceKindList: res.list
        })
      }, '获取失败');
  },
  nextStep:function(){
    let activeDot = this.data.activeDot;
    // 提交表单之后
    if (activeDot < 3) {
      this.setData({
        activeDot: activeDot + 1,
        activeDotList: util.createDotList(3, activeDot + 1)
      });
    }
    wx.setNavigationBarTitle({
      title: `保险代缴-${barTitleText[this.data.activeDot]}`
    })
  },
  //上一步
  prevStep: function () {
    let activeDot = this.data.activeDot,
      prevDot = activeDot - 1;
    // 提交表单之后
    if (activeDot < 3) {
      this.setData({
        activeDot: prevDot,
        activeDotList: util.createDotList(3, prevDot)
      }, () => {
        wx.setNavigationBarTitle({
          title: `添加车辆-${barTitleText[prevDot]}`
        })
      });
    }
  },
})